C语言位运算实现函数体
/*1、用位操作实现无符号整数的乘法运算,函数原型是unsigned int multiply(unsigned int x, unsigned int y);。例如:(11011)2×(10010)2=((11011)2<<1)+((11011)2<<4)。
(unsigned int 占用4个字节,共32位)*/
#include
unsigned int multiply(unsigned int a,unsigned int b)
{
int c =0,i = 0;
for (;i < 32;i ++ ) {
if(b&1) // 判断最低位是否为1
{
c = c + (a << i );//移i位相加
b>>=1;//b右移1位
}
else
{
b>>=1;
}
}
return c ;
}
int main ()
{
unsigned int x,y;
printf("Please input x and y value:");
scanf("%u%u",&x,&y);
printf("自动实现:%d*%d=%d\n",x,y,x*y);
printf("函数实现:%d*%d=%d\n",x,y, multiply(x,y));
return 0;
}
/*2、对一个32位无符号整数做循环右移,函数原型是unsigned int rotate_right(unsigned int x, int n);
所谓循环右移就是把低位移出去的部分再补到高位上去,例如rotate_right(0xdeadbeef, 8)的值应该是0xefdeadbe。*/
#include
unsigned int rotate_right(unsigned int x, int n);
int main()
{
unsigned int x;
int n ;
printf("Please input x and n:");
scanf("%u%d",&x,&n);
printf("x:%u\n",rotate_right(x, n));
return 0;
}
unsigned int rotate_right(unsigned int x, int n)
{
for (int i = 0;i < n ;i ++)// 循环n位
{
if (x&1)//判断最低位是否时1,如果是1就移到最高位,最高位加1
{
x = x >> 1;
x = x + 0x80000000;//x+=1<<31;
}
else
{
x = x >> 1;
}
}
return x;
}